package com.google.code.jholidays.events;

import com.google.code.jholidays.core.EventDescriptor;
import com.google.code.jholidays.events.parameters.DayMonthPair;
import com.google.code.jholidays.events.properties.FixedEventProperties;
import com.google.code.jholidays.parsers.FixedParser;

/**
 * Implements {@link AbstractFactory} for creating {@link FixedEvent} instances.
 * 
 * @author tillias
 * 
 */
public class FixedEventFactory extends AbstractFactory {

    /**
     * Creates new instance of factory
     */
    public FixedEventFactory() {
	parser = new FixedParser();
    }

    /**
     * {@inheritDoc}
     * <p>
     * This implementation attempts to parse {@link DayMonthPair} using
     * expression field provided by event descriptor. Another parameter
     * <tt>parent</tt> is not used so you can pass null instead
     * <p>
     * If event descriptor has valid expression method returns
     * {@link FixedEvent} instance. Otherwise returns null
     * 
     * @see #matches(EventDescriptor)
     */
    @Override
    protected AbstractEvent analizeExpression(EventDescriptor descriptor,
	    IEvent parent) {
	FixedEvent result = null;

	if (descriptor != null) {
	    try {
		DayMonthPair pair = parser
			.parseDate(descriptor.getExpression());
		if (pair != null) {
		    FixedEventProperties properties = new FixedEventProperties(
			    descriptor, pair);
		    result = new FixedEvent(properties);
		}
	    } catch (Exception e) {
		// nothing todo here
	    }
	}

	return result;
    }

    /**
     * {@inheritDoc}
     * <p>
     * This implementation checks whether event descriptor passed to method
     * isn't null. If descriptor is not null and descriptor's expression field
     * is valid for building {@link DayMonthPair} instance returns true.
     * <p>
     * If descriptor parameter passed to this method is null or expression field
     * of descriptor can't be used to create {@link DayMonthPair} returns false
     */
    @Override
    public boolean matches(EventDescriptor descriptor) {
	boolean result = false;

	if (descriptor != null)
	    result = parser.matches(descriptor.getExpression());

	return result;
    }

    FixedParser parser;
}
